package router

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type RedirectHandler struct {
}

func NewRedirectHandler() *RedirectHandler {
	return &RedirectHandler{}
}

func (handler *RedirectHandler) RegisterRoutes(r *gin.RouterGroup) {
	r.GET("/redirect", handler.Redirect)
	r.GET("/redirect_path", handler.RedirectPath)
}

func (handler *RedirectHandler) Redirect(ctx *gin.Context) {
	url := ctx.Query("url")
	if !isSafeUrl(url) {
		ctx.String(http.StatusBadRequest, "Invalid url")
		return
	}
	ctx.Redirect(http.StatusFound, url)
}

func (handler *RedirectHandler) RedirectPath(ctx *gin.Context) {
	path := ctx.Query("path")
	ctx.Redirect(http.StatusFound, "http://example.com/" + path)
}

func isSafeUrl(url string) bool {
	urlWhitelist := []string{"https://example.com/login", "https://example.com/logout"}
	for _, whiteUrl := range urlWhitelist {
		if url == whiteUrl {
			return true
		}
	}
	return false;
}
